var express = require('express');
var router = express.Router();
var execFile = require('child_process').execFile;
var fs = require('fs');
var dateFormat = require('../dateformat');
const path = require('path');
/* GET home page. */
router.get('/package', function (req, res, next) {
    var v = req.query.v;
    var branch = req.query.b;
    var versions = JSON.parse(fs.readFileSync(path.resolve(__dirname, '../version.json')));
    if (!v) {
        res.render('index', {title: '打包失败', content: '需要指定打包版本'});
        return;
    }
    if (!branch) {
        res.render('index', {title: '打包失败', content: '需要指定打包代码分支'});
        return;
    }

    var d = versions[v];
    var vShell = '';
    if (!d) {
        versions[v] = [0];
        vShell = v + 'b0';
    } else {
        var last = d[d.length - 1];
        var now = last + 1;
        vShell = v + '.b' + now;
        versions[v] = d.concat([now]);
    }
    fs.writeFile(path.resolve(__dirname, '../version.json'), JSON.stringify(versions, null, 2), 'utf8');

    var desc = '机器人于' + dateFormat(new Date(), 'yyyy/mm/dd_HH:MM:ss') + '提交上传';

    execFile(path.resolve(__dirname, '../mini.sh'), ['-V', vShell, '-D', desc, '-B', branch], {encoding: 'utf8'}, function (err, stdout, stderr) {
        if (err) {
            console.log(err);
            return;
        }
        console.log(stdout);
        console.log(stderr);
        var title = '打包成功';
        res.render('index', {title: title, content: stdout, error: stderr});
    });
});


router.get('/', function (req, res, next) {
    res.sendfile("index.html");
});

router.get('/help', function (req, res, next) {
    res.render('help', {
        title: '帮助',
        content: 'version 指定要打包的小程序版本  branch 指定要打包的代码分支',
        error: '例如 version=0.7.3 branch =dev 意思是 打包0.7.3这个版本，代码在dev分支上'
    });
});

module.exports = router;
